$(document).ready(function(){
    //图片预览
    imagePreview();

    //用户状态
    var username = getCookie('username'),
    usertype = getCookie('usertype');
    if(username && usertype){
        changeLoginStatus( 'login' , username , usertype );
    }else{
        changeLoginStatus( 'logout' , null , null );
    }

    //用户注册、登入、登出
    $( "#dialog:ui-dialog" ).dialog( "destroy" );

    var name = $( "#name" ),
    email = $( "#email" ),
    password = $( "#password" ),
    password_re = $( "#password-re" ),
    allFields = $( [] ).add( name ).add( email ).add( password );

    $( "#register_form" ).dialog({
        autoOpen: false,
        height: 300,
        width: 420,
        modal: true,
        buttons: {
            "注册": function() {
                var bValid = true;
                allFields.removeClass( "ui-state-error" );

                bValid = bValid && checkLength( name, "用户名", 3, 16 );
                bValid = bValid && checkLength( email, "Email", 6, 80 );
                bValid = bValid && checkLength( password, "密码", 5, 16 );

                bValid = bValid && checkRegexp( name, /^[0-9a-zA-Z\u4e00-\u9fa5_]([0-9a-zA-Z\u4e00-\u9fa5_])+$/i, "用户名格式错误" );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Email格式错误" );
                bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "密码格式错误" );

                bValid = bValid && checkPassword( password, password_re, "两次密码不相同" );

                if ( bValid ) {
                    $.post($('#APP_URL').val()+'/index.php',{
                        'm':'request',
                        'p':'user_action',
                        'action':'regist',
                        'username':name.val(),
                        'password':password.val(),
                        'email':email.val()
                        },function(data){
                        data = eval('('+data+')')
                        if(data.status == '1'){
                            changeLoginStatus('login',name.val(),'普通会员');
                            $("#register_form").dialog("close");
                        }else{
                            updateTips( data.i );
                        }
                    });

                }
            },
            "取消": function() {
                $( this ).dialog("close");
            }
        },
        close: function() {
            allFields.val("").removeClass( "ui-state-error" );
        }
    });
    $( "#login_form" ).dialog({
        autoOpen: false,
        height: 220,
        width: 250,
        modal: true,
        buttons: {
            "登入": function() {
                $.post($('#APP_URL').val()+'/index.php',{
                    'm':'request',
                    'p':'user_action',
                    'action':'login',
                    'username':$('#login_name').val(),
                    'password':$('#login_password').val()
                    },function(data){
                    data = eval('('+data+')')
                    if(data.status == '1'){
                        changeLoginStatus('login',$('#login_name').val(),data.info);
                        $("#login_form").dialog("close");
                    }else{
                        updateTips(data.info);
                    }
                });
            },
            "取消": function() {
                $( this ).dialog("close");
            }
        },
        close: function() {
            allFields.val("").removeClass("ui-state-error");
        }
    });
    $("#logout_form").dialog({
        autoOpen: false,
        height: 300,
        width: 420,
        modal: true,
        open: function(){
            $.post($('#APP_URL').val()+'/index.php',{
                'm':'request',
                'p':'user_action',
                'action':'logout'
            },function(data){
                data = eval('('+data+')')
                if(data.status == '1'){
                    changeLoginStatus('logout', null , null )
                    $("#logout_form").dialog( "close" );
                }else{
                    updateTips( data.info );
                }
            });
        },
        close: function() {
            allFields.val( "" ).removeClass( "ui-state-error" );
        }
    });

    bindAction();
});

//变更会员区状态
function changeLoginStatus( type , username , usertype ){
    if(type == 'login'){
        var goods_nums = getCookie('goods_nums'),total_price = getCookie('total_price');
        $('#goods_nums').html(goods_nums ? parseInt(goods_nums) : '0');//parseInt(goods_nums));
        $('#total_price').html(total_price ? parseFloat(total_price) : '0.00');//parseFloat(total_price));
        $('#memberzone').html('您好，'+username+'（'+usertype+'）'+' <a id="logout_link" href="javascript:void(0)" class="f_red">注销</a>');
    }else{
        $('#goods_nums').html('0');
        $('#total_price').html('0.00');
        $('#memberzone').html('欢迎光临&nbsp;&nbsp;&nbsp;&nbsp;<a id="login_link" href="javascript:void(0)" class="f_red">登录</a> | <a id="register_link" href="javascript:void(0)" class="f_red">注册</a>');
    }
    bindAction();
}
//更新提示信息
function updateTips( t ) {
    var tips = $( ".validateTips" );
    tips
    .text( t )
    .addClass( "ui-state-highlight" );
    setTimeout(function() {
        tips.removeClass( "ui-state-highlight", 1500 );
    }, 500 );
}
//数据验证
function checkPassword( a, b,n ){
    if(a.val() == b.val()){
        return true;
    }else{
        a.addClass( "ui-state-error" );
        b.addClass( "ui-state-error" );
        updateTips( n );
        return false;
    }
}
function checkLength( o, n, min, max ) {
    if ( o.val().length > max || o.val().length < min ) {
        o.addClass( "ui-state-error" );
        updateTips( n + "的长度应在" +
            min + " 和 " + max + "之间." );
        return false;
    } else {
        return true;
    }
}
function checkRegexp( o, regexp, n ) {
    if ( !( regexp.test( o.val() ) ) ) {
        o.addClass( "ui-state-error" );
        updateTips( n );
        return false;
    } else {
        return true;
    }
}
//绑定事件
function bindAction(){
    $("#register_link").click(function() {
        $("#register_form" ).dialog("open");
    });
    $("#login_link").click(function() {
        $("#login_form" ).dialog("open");
    });
    $("#logout_link").click(function() {
        $("#logout_form" ).dialog("open");
    });
}
//搜索
function checkSearchForm(){
    if(document.getElementById('keyword').value!="请输入关键词")
    {
        return true;
    }
    else
    {
        document.getElementById('keyword').value="请输入关键词";
        alert("请输入关键词");
        return false;
    }
}
function checkSearchX(o){
    if(o.value=="请输入关键词")
    {
        o.value="";
    }
}

function BlurSearchX(o){
    if(o.value=="")
    {
        o.value="请输入关键词";
    }
}
//初始化主菜单
function sw_nav(obj,tag){
    var subdivs = obj.getElementsByTagName("div");
    var ifs = obj.getElementsByTagName("iframe");

    if(subdivs.length>0){
        if(tag==1){
            subdivs[0].style.display = "block";
            ifs[0].style.display = "block";
        }else{
            subdivs[0].style.display = "none";
            ifs[0].style.display = "none";
        }
    }
}
//Cookie
function SetCookie(name,value){//两个参数，一个是cookie的名子，一个是值
    var Days = 30; //此 cookie 将被保存 30 天
    var exp  = new Date();    //new Date("December 31, 9998");
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name){//取cookies函数
    var arr = document.cookie.match(new RegExp("(^| )"+$('#COOKIE_PRE').val()+name+"=([^;]*)(;|$)"));
    if(arr != null) return decodeURIComponent(arr[2]);return null;

}
function delCookie(name){//删除cookie
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
/*
function URLdecode(str) {
    var ret = "";
    for(var i=0;i<str.length;i++) {
        var chr = str.charAt(i);
        if(chr == "+") {
            ret += " ";
        }else if(chr=="%") {
            var asc = str.substring(i+1,i+3);
            if(parseInt("0x"+asc)>0x7f) {
                ret += decodeURI("%"+ str.substring(i+1,i+9));
                i += 8;
            }else {
                ret += String.fromCharCode(parseInt("0x"+asc));
                i += 2;
            }
        }else {
            ret += chr;
        }
    }
    return ret;
}
*/